<!-- components/WangEditor.vue -->
<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      style="border-bottom: 1px solid #ccc"
    />
    <Editor
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="'default'"
      style="height: 300px; overflow-y: auto"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 必须引入样式
import { onBeforeUnmount, shallowRef, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { uploadAvatarFile } from '@/apis/file.js'

const props = defineProps({
  modelValue: String,
})
const emit = defineEmits(['update:modelValue'])

const editorRef = shallowRef()

// 双向绑定内容
const valueHtml = shallowRef(props.modelValue || '')

watch(valueHtml, (newVal) => {
  emit('update:modelValue', newVal)
})

// 工具栏配置
const toolbarConfig = {
  excludeKeys: [], // 可移除某些按钮
}

// 编辑器配置
const editorConfig = {
  placeholder: '请输入正文内容...',
  MENU_CONF: {
    uploadImage: {
      async customUpload(file, insertFn) {
        const formData = new FormData()
        formData.append('file', file)
        const res = await uploadAvatarFile(formData)
        const url = res.data
        insertFn(url) // 插入图片
      },
    },
  },
}

const handleCreated = (editor) => {
  editorRef.value = editor
}

onBeforeUnmount(() => {
  editorRef.value?.destroy()
})

// 新增手动设置内容的方法
const setHtml = (html) => {
  if (!editorRef.value) return
  editorRef.value.setHtml(html)
}

// 暴露方法给父组件
defineExpose({ setHtml })
</script>
